package me.flyray.crm.core.modules.netty.service;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.github.wxiaoqi.security.biz.common.crm.request.LockManagerReq;
import com.github.wxiaoqi.security.biz.common.msg.BizResponseCode;
import com.github.wxiaoqi.security.common.util.EntityUtils;

import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import me.flyray.crm.core.modules.netty.entity.SolidLock;
import me.flyray.crm.core.modules.netty.handlers.LocksMap;
import me.flyray.crm.core.modules.netty.handlers.NettyChannelMap;

@Service
public class LockManageService {
	
	private final static Logger logger = LoggerFactory.getLogger(LockManageService.class);

	public Map<String, Object> lockStateManage(LockManagerReq params) {
		logger.info("开锁参数。。。{}"+EntityUtils.beanToMap(params));
		Map<String, Object> response = new HashMap<String, Object>();
		//开锁命令 open
		String order = params.getState();
		logger.info("修改锁状态。。。开锁命令 {}"+order);
		//获取指定的锁信息-锁id lockId
        SolidLock lock=(SolidLock) LocksMap.get(params.getLockId());
        Channel channel = NettyChannelMap.get(params.getLockId());
        
        Map<String, String> param = new HashMap<String, String>();
        param.put("lockId", params.getLockId());
        param.put("state", order);
        param.put("type", "requestLock");
        
        if(null!=channel&&null!=lock){
        	try {
        		synchronized(LocksMap.get(params.getLockId())){//map  open
//        			channel.writeAndFlush(Unpooled.copiedBuffer(JSONObject.fromObject(param).toString().getBytes()));
        			channel.writeAndFlush(Unpooled.copiedBuffer(order.getBytes()));
        			lock.wait(1000);
        		}
			} catch (InterruptedException e) {
				e.printStackTrace();
				response.put("code",BizResponseCode.LOCK_HANDLE_FAILED.getCode());
				response.put("message",BizResponseCode.LOCK_HANDLE_FAILED.getMessage());
				return response;
			}
        	String state = lock.getState();
        	logger.info("开锁状态---"+state);
        	if (state.equals("00")) {
    			response.put("code","00");
				response.put("message","开门成功");
    			lock.setState("01");
			}else {
				response.put("code",lock.getState());
				response.put("message","开门失败");
				lock.setState("01");
			}
			return response;
        }
        response.put("code",BizResponseCode.LOCK_HANDLE_FAILED.getCode());
		response.put("message",BizResponseCode.LOCK_HANDLE_FAILED.getMessage());
		return response;
    }
	
}
